package com.qf.lanzhou.shop.api.controller;

import com.alibaba.fastjson.JSON;
import com.qf.lanzhou.shop.api.dao.ReceivingAddressMapper;
import com.qf.lanzhou.shop.api.exceptions.BaseExceptions;
import com.qf.lanzhou.shop.api.service.impl.OrderServiceImpl;
import com.qf.lanzhou.shop.pojo.entity.*;
import com.qf.lanzhou.shop.pojo.qo.OrderAndAddress;
import com.qf.lanzhou.shop.pojo.qo.OrderParm;
import com.qf.lanzhou.shop.pojo.vo.BaseRespVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author jack
 */
@RestController
@Api(tags = "订单接口")
public class OrderController extends BaseController {
    @Autowired
    private OrderServiceImpl osi;

    @Autowired
    private ReceivingAddressMapper receivingAddressMapper;

    @ApiOperation(value = "订单生成接口")
    @PostMapping(value = "/generateOrders")
//    @RequestParam(value = "arr[][]") Long[][] arr
    public BaseRespVO generateOrders(String arr, HttpServletRequest req) {
        User user = (User) req.getSession().getAttribute("user");
        if (user == null) {
           throw new BaseExceptions(300,"11");
        }
        ArrayList<SonOrder> list1 = new ArrayList<>();
        //接收参数开始
//        arr = "[{\"sellerId\":\"1\",\"id\":\"7\"},{\"sellerId\":\"1\",\"id\":\"5\"},{\"sellerId\":\"2\",\"id\":\"2\"}]";
        List<Goods> parse = JSON.parseArray(arr, Goods.class);
        System.out.println("test:" + parse);
        Map<Long, List> map = new HashMap<>();
        List<Long> list = new ArrayList<>();
        for (int i = 0; i < parse.size(); i++) {
            if (list.size() == 0) {
                list.add(parse.get(i).getId());
            } else if
            (parse.get(i).getSellerId().equals(parse.get(i - 1).getSellerId())) {
                list.add(parse.get(i).getId());
            } else {
                list = new ArrayList<>();
                list.add(parse.get(i).getId());
            }
            map.put(parse.get(i).getSellerId(), list);
        }
        //接收参数结束
        //参数格式为map(卖家ID，商品IDList集合)
        //通过一行商品ID查询一组子订单列表

        //遍历map
        //map多长就有但是个父订单 value为list（商品ID） value就是子订单
        Set<Map.Entry<Long, List>> entrySet = map.entrySet();
        Iterator<Map.Entry<Long, List>> iterator = entrySet.iterator();
        Long sellerId;
        while (iterator.hasNext()) {
            sellerId = iterator.next().getKey();
            OrderParm orderParm = new OrderParm();
            orderParm.setList(map.get(sellerId));
            orderParm.setUserId(user.getId());
            List<SonOrder> sonOrders = osi.getSonsOrder(orderParm);
            //获取卖家名
            String sellerName = osi.getSellerName(sellerId);
            //创建父订单
            ParentsOrder parentsOrder = new ParentsOrder();
            //父订单需要1.用户ID 2.用户默认地址 3.卖家id 4.总价格5.发货地址
            //userId后期从siession中获取
            parentsOrder.setUserId(user.getId());
            //获取默认用户默认地址
            ReceivingAddress receivingAddress = receivingAddressMapper.selectUserDefaultAddress(user.getId());
            if (receivingAddress!=null){
                parentsOrder.setReceivingAddressId(receivingAddress.getId());
            }
            parentsOrder.setSellerId(sellerId);
            BigDecimal bigDecimal = new BigDecimal(0);
            //获取父订单总价格
            for (int j = 0; j < sonOrders.size(); j++) {
                BigDecimal num = new BigDecimal(sonOrders.get(j).getGoodsNumber());
                sonOrders.get(j).setSonOrderAmout(sonOrders.get(j).getOriginalPrice().multiply(num));
                bigDecimal = bigDecimal.add(sonOrders.get(j).getSonOrderAmout());
            }
            parentsOrder.setAmount(bigDecimal);
            parentsOrder.setShippingAddress("天河B6");
            boolean b = osi.insertParents(parentsOrder);
            if (b) {
                return convertErrorResult("生成订单失败");
            }

            for (int j = 0; j < sonOrders.size(); j++) {
                //创建子订单
                sonOrders.get(j).setParentsOrderId(parentsOrder.getId());
                boolean b1 = osi.insertSon(sonOrders.get(j));
                if (b1) {
                    return convertErrorResult("生成子订单失败,详情看后台");
                }

        }
            for (int i = 0; i < sonOrders.size(); i++) {
                sonOrders.get(i).setSellerName(sellerName);

                list1.add(sonOrders.get(i));
            }
            System.out.println(list1);
        }
        return convertSuccessResult(list1);

//        for (int i = 0; i < map.size(); i++) {
//            //一组子订单列表生成一个父订单
//            List<SonOrder> sonsOrders = osi.getSonsOrder(arr1[i]);
//            System.out.println(arr1[i]);
//            System.out.println("子订单长度： " + sonsOrders.size());
//            System.out.println("子订单内容： " + sonsOrders);
//            ParentsOrder parentsOrder = new ParentsOrder();
//            //父订单需要1.用户ID 2.用户默认地址 3.卖家id 4.总价格5.发货地址
//            //userId后期从siession中获取
//            parentsOrder.setUserId(user.getId());
//            //获取默认用户默认地址
//            receivingAddressMapper.selectUserDefaultAddress(user.getId());
//            parentsOrder.setReceivingAddressId(1L);
//            parentsOrder.setSellerId(sonsOrders.get(i).getSellerId());
//            BigDecimal bigDecimal = new BigDecimal(0);
//            //获取父订单总价格
//            for (int j = 0; j < sonsOrders.size(); j++) {
//                BigDecimal num = new BigDecimal(sonsOrders.get(j).getGoodsNumber());
//                sonsOrders.get(j).setSonOrderAmout(sonsOrders.get(j).getOriginalPrice().multiply(num));
//                bigDecimal = bigDecimal.add(sonsOrders.get(j).getSonOrderAmout());
//            }
//            parentsOrder.setAmount(bigDecimal);
//            parentsOrder.setShippingAddress("天河B6");
//            boolean b = osi.insertParents(parentsOrder);
//            if (b) {
//                return convertErrorResult("生成订单失败");
//            }
//            System.out.println("生成父订单: " + parentsOrder);
//            //父订单生成成功 生成对应的子订单
//            for (int j = 0; j < sonsOrders.size(); j++) {
//                sonsOrders.get(j).setParentsOrderId(parentsOrder.getId());
//                boolean b1 = osi.insertSon(sonsOrders.get(j));
//                if (b1) {
//                    return convertErrorResult("生成子订单失败,详情看后台");
//                }
//                System.out.println("生成子订单: " + sonsOrders);
//            }
//            list.add(sonsOrders);
//        }
//        System.out.println("返回结果前日志");
//        System.out.println(list);
//        //查询
    }

    @GetMapping(value = "/testController")
    @ApiOperation(value = "测试接口")
    public BaseRespVO testController(@RequestParam(value = "arr[][]") Long[][] arr) {
        System.out.println("测试接口今日" + arr);
        System.out.println(arr.length);
        return null;
    }

    @ApiOperation(value = "生成单个子订单")
    @PostMapping(value = "/generateOrdersSingle")
    public BaseRespVO generateOrdersSingle(SonOrder sonOrder, HttpServletRequest req) {
        System.out.println("生成单个子订单");
        //生成一个父订单
        System.out.println("sonOrder" + sonOrder);
        ParentsOrder parentsOrder = new ParentsOrder();
        //父订单需要1.用户ID 2.用户默认地址 3.卖家id 4.总价格5.发货地址
        //userId后期从siession中获取
        User user = (User) req.getSession().getAttribute("user");
        if (user == null) {
            throw new BaseExceptions(300,"11");
        }
        parentsOrder.setUserId(user.getId());
        ReceivingAddress receivingAddress = receivingAddressMapper.selectUserDefaultAddress(user.getId());

        parentsOrder.setReceivingAddressId(receivingAddress.getId());
        parentsOrder.setSellerId(1L);
        BigDecimal num = new BigDecimal(sonOrder.getGoodsNumber());
        parentsOrder.setAmount(num.multiply(sonOrder.getOriginalPrice()));
        parentsOrder.setShippingAddress("黑洞");
        System.out.println("生成父订单前");
        System.out.println(parentsOrder);
        boolean b = osi.insertParents(parentsOrder);
        System.out.println(parentsOrder);
        System.out.println(b);
        if (b) {
            return convertErrorResult("生成订单失败");
        }
        //生成子订单
        System.out.println(parentsOrder.getId());
        sonOrder.setParentsOrderId(parentsOrder.getId());
        sonOrder.setSonOrderAmout(num.multiply(sonOrder.getOriginalPrice()));
        System.out.println("生成子订单前");

        if (osi.insertSon(sonOrder)) {
            convertErrorResult("生成订单失败");
        }
        System.out.println("返回");
        return convertSuccessResult(sonOrder);
    }

    @ApiOperation(value = "确认单个订单")
    @PostMapping(value = "/ConfirmOrderSingle")
    public BaseRespVO ConfirmOrderSingle(Long id) {
        System.out.println(id);
        //传进来子ID
        //通过子ID获取子订单 父订单
        SonOrder sonOrder = osi.selectSonOrderById(id);
        System.out.println("子订单： " + sonOrder);

        ParentsOrder parentsOrder1 = osi.selectBySonOrderId(id);
        System.out.println("父订单： " + parentsOrder1);
        //通过父订单获取地址信息
        ConfirmOrder confirmOrder = new ConfirmOrder();
        ReceivingAddress receivingAddress = osi.selectAddressByParentsId(parentsOrder1.getId());
        if (receivingAddress == null || "".equals(receivingAddress)) {
            return convertErrorResult("没有默认地址也没有选择地址");
        }
        System.out.println("地址信息： " + receivingAddress);
        //给确认订单实体大哥赋值
        confirmOrder.setAddressProvince(receivingAddress.getAddressProvince());
        confirmOrder.setAddressCity(receivingAddress.getAddressCity());
        confirmOrder.setAddressDistrict(receivingAddress.getAddressDistrict());
        confirmOrder.setReceivingName(receivingAddress.getReceivingName());
        confirmOrder.setReceivingPhone(receivingAddress.getReceivingPhone());
        confirmOrder.setGoodsName(sonOrder.getGoodsName());
        confirmOrder.setOriginalPrice(sonOrder.getOriginalPrice());
        confirmOrder.setSonOrderAmout(sonOrder.getSonOrderAmout());
        confirmOrder.setGoodsNumber(sonOrder.getGoodsNumber());
        confirmOrder.setAddressDetails(receivingAddress.getAddressDetails());
//        private String addressProvince;
//        private String addressCity;
//        private String addressDistrict;
//        private String receivingName;
//        private Long receivingPhone;
//        private String goodsName;
//        private BigDecimal originalPrice;
//        private BigDecimal sonOrderAmout;
//        private Long goodsNumber;
        System.out.println(confirmOrder);
        return convertSuccessResult(confirmOrder);
    }

    @ApiOperation(value = "确认订单")
    @PostMapping(value = "/ConfirmOrder")
    public BaseRespVO ConfirmOrder(Long id) {
        System.out.println(id);
        //传进来父ID
        //通过子ID获取子订单 父订单
//        SonOrder sonOrder = osi.selectSonOrderById(id);
//        System.out.println("子订单： " + sonOrder);
//
//        ParentsOrder parentsOrder1 = osi.selectBySonOrderId(id);
//        System.out.println("父订单： " + parentsOrder1);
        //通过父订单获取地址信息
        ReceivingAddress receivingAddress = osi.selectAddressByParentsId(id);
        if (receivingAddress == null || "".equals(receivingAddress)) {
            return convertErrorResult("没有默认地址，也没有选择地址");
        }
        System.out.println("地址信息： " + receivingAddress);
        //获取父订单
        ParentsOrder parentsOrder = osi.gerParentsOrder(id);
        //获取所有子订单
        List<SonOrder> sonOrders = osi.selectSonOrder(id);
        CofimAllOrder cofimAllOrder = new CofimAllOrder();
        cofimAllOrder.setAddressDetails(receivingAddress.getAddressDetails());
        cofimAllOrder.setAmount(parentsOrder.getAmount());
        cofimAllOrder.setSonOrders(sonOrders);
        //通过父订单ID获取子订单
        //给确认订单实体大哥赋值
//        ConfirmOrder confirmOrder = new ConfirmOrder();
//        confirmOrder.setAddressProvince(receivingAddress.getAddressProvince());
//        confirmOrder.setAddressCity(receivingAddress.getAddressCity());
//        confirmOrder.setAddressDistrict(receivingAddress.getAddressDistrict());
//        confirmOrder.setReceivingName(receivingAddress.getReceivingName());
//        confirmOrder.setReceivingPhone(receivingAddress.getReceivingPhone());
//        confirmOrder.setGoodsName(sonOrder.getGoodsName());
//        confirmOrder.setOriginalPrice(sonOrder.getOriginalPrice());
//        confirmOrder.setSonOrderAmout(sonOrder.getSonOrderAmout());
//        confirmOrder.setGoodsNumber(sonOrder.getGoodsNumber());
//        confirmOrder.setAddressDetails(receivingAddress.getAddressDetails());
//        System.out.println(confirmOrder);
        return convertSuccessResult(cofimAllOrder);
    }

    @GetMapping(value = "/selectaddress")
    @ApiOperation(value = "选择地址")
    public BaseRespVO selectAddress(Long id1, Long id2) {
        System.out.println(id1 + "   " + id2);
        ParentsOrder parentsOrder = osi.selectBySonOrderId(id2);
        OrderAndAddress oaa = new OrderAndAddress();
        oaa.setAddressId(id1);
        oaa.setParentsId(parentsOrder.getId());
        boolean b = osi.selectAddress(oaa);
        if (b) {
            return convertErrorResult("系统繁忙");
        }
        return convertSuccessResult("哦哦哦，哦哦哦黑猫警长");
        //获取父订单 把父订单的地址改变
    }

}
